#!/bin/bash

BASEDIR=$(cd "$(dirname "$0")"; pwd)
TMPDIR=tmp
[[ "$1" == "--latest" ]] && NGINXV=nginx-1.11.8 || NGINXV=nginx-1.10.2
echo "nginx version "$NGINXV" selected" 
NGINXDIR=$NGINXV/

# Create and move into the tmp dirctory
mkdir -p $TMPDIR
cd $TMPDIR

# Download nginx source


if [ ! -f $NGINXV.tar.gz ]; then
	echo "Downloading nginx."
	if hash curl 2>/dev/null; then
		(curl http://nginx.org/download/$NGINXV.tar.gz --silent -o $NGINXV.tar.gz) > /dev/null
	else
		echo "curl not found, falling back to wget."
		(wget http://nginx.org/download/$NGINXV.tar.gz --quiet -O $NGINXV.tar.gz) > /dev/null
	fi
else
	echo "nginx already downloaded."
fi

# Unpack nginx source
echo "Extracting file."
tar zxf ./$NGINXV.tar.gz

cd ./$NGINXDIR

# Configure and make
echo "Configuring executable."
./configure --prefix=. --sbin-path=bin/ --conf-path=conf/nginx.conf --error-log-path=logs/error.log --http-client-body-temp-path=tmp/client_body_temp/ --http-proxy-temp-path=tmp/proxy_temp/ --http-fastcgi-temp-path=tmp/fastcgi_temp/ --http-uwsgi-temp-path=tmp/uwsgi_temp/ --http-scgi-temp-path=tmp/scgi_temp/ --with-ipv6 --with-http_ssl_module --with-http_gzip_static_module --with-http_stub_status_module --without-mail_pop3_module --without-mail_imap_module --without-mail_smtp_module --without-http_fastcgi_module > ../../logs/compile.log

echo "Building executable."
make >> ../../logs/compile.log

# Move bin file into appropriate dir
if [ ! -d $BASEDIR/bin/ ]; then
	mkdir $BASEDIR/bin
fi

cp -f objs/nginx $BASEDIR/bin/

cd $BASEDIR

# Remove the temporary directory
echo "Cleaning up."
rm -r $TMPDIR/$NGINXV && rm -r $TMPDIR/$NGINXV.tar.gz
